package com.funkyfurrymonkey.world2d;
import box2D.collision.B2SeparationFunction;
import box2D.collision.shapes.B2PolygonShape;
import box2D.dynamics.B2BodyDef;
import box2D.dynamics.B2FixtureDef;
import box2D.dynamics.B2Fixture;
import box2D.common.math.B2Vec2;
import box2D.dynamics.B2Body;
import box2D.dynamics.B2World;
import com.funkyfurrymonkey.utils.Utils;
import openfl.Vector;
import openfl.display.Bitmap;
import openfl.display.BitmapData;
import openfl.display.Sprite;
import openfl.geom.Point;
import workbench.actors.Object2dData;


/**
 * ...
 * @author Marcos Martinez
 */
class StaticActor 
{
	private var m_cWorld:B2World;
	private var m_bmCostum:Bitmap;
	public var m_cCanvas:Sprite;
	
	private var m_cPos:Point;
	private var m_cVec:Array<B2Vec2>;
	private var m_cBody:B2Body;
	public function new(cWorld:B2World) 
	{
		//super();
		m_cWorld = cWorld;
	}
	
	public function setProps(bmCostum:Bitmap, cPos:Point, arrShape:Array<Point>)
	{
		m_cPos = cPos;
		m_bmCostum = bmCostum;
		m_bmCostum.x = 0;// -m_bmCostum.width / 2;
		m_bmCostum.y =  -m_bmCostum.height ;
		m_cCanvas = new Sprite();
		m_cCanvas.addChild(m_bmCostum);
		m_cCanvas.x = cPos.x;
		m_cCanvas.y = cPos.y ;
		
		
		//var a:Array <Point>= calcVertex(m_bmCostum.bitmapData);
		//trace("points : "+a.length);
		
		m_cVec = new Array<B2Vec2>();
		//for (each in a)
		for (each in arrShape)
		{
			var vec:B2Vec2 = new B2Vec2(each.x, each.y);
			m_cVec.push(vec);
		}
			
		
		
		
	}
	public function create(obj:Dynamic):Void
	{
		var groundBodyDef:B2BodyDef = new B2BodyDef();
		groundBodyDef.position.set(m_cPos.x , m_cPos.y );
		 m_cBody = m_cWorld.createBody(groundBodyDef);
		var groundShape:B2PolygonShape = new B2PolygonShape();
		groundShape.setAsVector(m_cVec);
		var groundFixtureDef:B2FixtureDef = new B2FixtureDef();
		groundFixtureDef.shape = groundShape;

		m_cBody.setUserData(obj);
		
		m_cBody.createFixture(groundFixtureDef);
	
	}
	
	private function calcVertex(cBitmapData:BitmapData ):Array<Point>
	{
		var arrPoints:Array<Point> = new Array<Point>();
	
		var cPixels:Vector<UInt> = cBitmapData.getVector(cBitmapData.rect);
		var nPrev:UInt = 0;
		for (nRelpos in 0...cPixels.length)
		{		
			if (cPixels[nRelpos] != nPrev && (nPrev == 0 || cPixels[nRelpos] == 0) )
			{
				var cPoint = Utils.getPosInArray(nRelpos, cBitmapData.width, cBitmapData.height);
				arrPoints.push(new Point(cPoint.x, cPoint.y) );
			}
		
			
			nPrev = cPixels[nRelpos] ;
			
		}
		return arrPoints;
	}
	
	
}